package com.wtpaint.algorithm;

import java.lang.reflect.Method;
import java.util.Random;

public class SortUtil {


    public static Integer[] generateRandomArray(int n, int rangeL, int rangeR) {
        assert rangeL <= rangeR;
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++) {
            arr[i] = new Random().nextInt(rangeR - rangeL) + rangeL;
        }
        return arr;
    }

    public static boolean isSort(Comparable[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].compareTo(arr[i + 1]) > 0) {
                return false;
            }
        }
        return true;
    }

    public static void testSort(String sortName, Comparable[] arr) {

        try {
            Class sortClass = Class.forName(sortName);
            Method sortMethod = sortClass.getMethod("sort", new Class[]{Comparable[].class});
            Object[] params = new Object[]{arr};
            long start = System.currentTimeMillis();
            sortMethod.invoke(null, params);
            long end = System.currentTimeMillis();
            assert isSort(arr);
            System.out.println(sortClass.getSimpleName() + ":" + (end - start) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printArray(Object[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            System.out.print(' ');
        }
        System.out.println();
    }

}
